<?php


namespace app\admin\controller\Shop;



use app\admin\controller\BaseController;
use app\admin\model\Shop\ShopGoodsAttrModel;
use app\admin\model\Shop\ShopGoodsAttrValueModel;
use app\admin\model\Shop\ShopGoodsCateRelationModel;
use app\admin\model\Shop\ShopGoodsModel;
use app\Utils\ImageUtil;
use app\Utils\Util;
use Exception;
use think\facade\Db;
use think\Request;

class ShopGoods extends BaseController
{

    /**
     * 分页查询
     * @param Request $request
     * @return array
     */
    public function getShopGoodsList(Request $request)
    {
        $param = $request->param();
        $where = [];
        $page = $param['page'];
        $limit = $param['limit'];
        $good_name = !empty($param['good_name']) ? $param['good_name'] : "";
        $is_show = !empty($param['is_show']) ? $param['is_show'] : "";
        $is_del = !empty($param['is_del']) ? $param['is_del'] : "";
        if (empty($page)) {
            $page = 1;
        }
        if (empty($limit)) {
            $limit = 10;
        }
        if (!empty($good_name)) {
            array_push($where, ['good_name', 'like', '%' . $good_name . '%']);
        }
        if (!empty($is_show)) {
            if ($is_show == 1) {
                array_push($where, ['is_show', '=', 1]);
            }
            if ($is_show == 2) {
                array_push($where, ['is_show', '=', 0]);
            }
        }
        if (!empty($is_del)) {
            if ($is_del == 1) {
                array_push($where, ['is_del', '=', 0]);
            }
            if ($is_del == 2) {
                array_push($where, ['is_del', '=', 1]);
            }
        }
        $list = ShopGoodsModel::getShopGoodsListWhere($page, $limit, $where);
        $count = ShopGoodsModel::getShopGoodsCountWhere($where);
        foreach ($list as &$item){
            $item['img'] = ImageUtil::i()->replaceUrl($item['img']);
            $images = !empty($item['slider_img']) ? json_decode($item['slider_img'],true) : [];
            foreach ($images as &$image){
                $image = ImageUtil::i()->replaceUrl($image);
            }
            $item['slider_img'] = $images;
            $item['details'] = !empty($item['details']) ? htmlspecialchars_decode($item['details']) : "";

            $attr = ShopGoodsAttrModel::getShopGoodsAttrWhereMore([['goods_id','=',$item['id']]]);
            if(!empty($attr)){
                foreach ($attr as &$it){
                    $it['attr_values'] = explode(",",$it['attr_values']);
                }
                $item['attr'] = $attr;
                $item['attr_value'] = ShopGoodsAttrValueModel::getShopGoodsAttrValueWhereMore([['goods_id','=',$item['id']]]);
            }
        }
        return Util::returnPageJson(self::CODE_DATA, $count, $list, "");
    }


    /**
     * 添加
     * @param Request $request
     * @return array
     */
    public function addShopGoods(Request $request)
    {
        $param = $request->param();

        $data = [
            'good_name' => $param['good_name'],
            'brief' => $param['brief'],
            'key' => $param['key'],
            'integral' => $param['integral'],
            'price' => $param['price'],
            'vip_price' => !empty($param['vip_price']) ? $param['vip_price'] : 0,
            'cost_price' => $param['cost_price'],
            'postage' => $param['postage'],
            //'unit_id' => $param['unit_id'],
            'sort' => $param['sort'],
            'stock' => $param['stock'],
            //'details' => htmlspecialchars($param['details']),
            'ficti' => $param['ficti'],
            'browse' => $param['browse'],
            'is_hot' => !empty($param['is_hot']) ? 1 : 0,
            'is_benefit' => !empty($param['is_benefit']) ? 1 : 0,
            'is_best' => !empty($param['is_best']) ? 1 : 0,
            'is_new' => !empty($param['is_new']) ? 1 : 0,
            'is_postage' => !empty($param['is_postage']) ? 1 : 0,
            'up_time' => date("Y-m-d H:i:s",time())
        ];

        //图片上传(单图)
        if (!empty($request->file('file'))) {
            $file = $request->file('file');
            $path = "/shop/goods/product/img/";
            $url = ImageUtil::i()->upload($file, $path);
        }
        //多图
        if (!empty($request->file('files'))) {
            $files = $request->file('files');
            $path = "/shop/goods/product/slider_img/";
            $urls = ImageUtil::i()->upload($files, $path);
        }

        if (!empty($url)) {
            $data['img'] = $url;
        }
        if (!empty($urls)) {
            $data['slider_img'] = json_encode($urls);
        }

        if (!empty($param['is_show']) && $param['is_show'] == "on") {
            $data['is_show'] = 1;
        }
        if (!empty($param['is_del']) && $param['is_del'] == "on") {
            $data['is_del'] = 1;
        }

        DB::startTrans();
        try{
            $id = ShopGoodsModel::addShopGoods($data);
            if(!empty($param['select'])){
                $cate_ids = explode(',',$param['select']);
                $data = [];
                foreach ($cate_ids as $cate_id){
                    $arr['goods_id'] = $id;
                    $arr['cate_id'] = $cate_id;
                    $arr['add_time'] = date("Y-m-d H:i:s",time());
                    array_push($data,$arr);
                }
                ShopGoodsCateRelationModel::addShopGoodsCateRelation($data);
            }
            //有属性
            if(!empty($param['attr'])){
                foreach ($param['attr'] as $item){
                    $attr_data = [
                        'goods_id'=>$id,
                        'attr_name'=>$item[0],
                        'attr_values'=>$item[1]
                    ];
                    ShopGoodsAttrModel::addShopGoodsAttr($attr_data);
                }
                if(!empty($param['suk'])){
                    foreach ($param['suk'] as $k=>$item){
                        $attr_value = [
                            'goods_id'=>$id,
                            'suk'=>$param['suk'][$k],
                            'stock'=>!empty($param['attr_stock'][$k]) ? $param['attr_stock'][$k] : 0,
                            'sales'=>!empty($param['attr_sales'][$k]) ? $param['attr_sales'][$k] : 0,
                            'integral'=>!empty($param['attr_integral'][$k]) ? $param['attr_integral'][$k] : 0,
                            'price'=>!empty($param['attr_price'][$k]) ? $param['attr_price'][$k] : 0,
                            'vip_price'=>!empty($param['attr_vip_price'][$k]) ? $param['attr_vip_price'][$k] : 0,
                            'unique'=>uniqid($id),
                            'cost'=>!empty($param['attr_cost'][$k]) ? $param['attr_cost'][$k] : 0,
                        ];
                        ShopGoodsAttrValueModel::addShopGoodsAttrValue($attr_value);
                    }
                }
            }
            DB::commit();
            return Util::returnJson(self::CODE_SUCCESS, null, "添加成功");
        }catch (Exception $e){
            DB::rollBack();
            return Util::returnJson(self::CODE_ERROR, null, "添加失败2");
        }
    }

    /**
     * 更新
     * @param Request $request
     * @return array
     */
    public function editShopGoods(Request $request)
    {
        $param = $request->param();

        $save = [
            'good_name' => $param['good_name'],
            'brief' => $param['brief'],
            'key' => $param['key'],
            'integral' => $param['integral'],
            'price' => $param['price'],
            'vip_price' => !empty($param['vip_price']) ? $param['vip_price'] : 0,
            'cost_price' => $param['cost_price'],
            'postage' => $param['postage'],
            //'unit_id' => $param['unit_id'],
            'sort' => $param['sort'],
            'stock' => $param['stock'],
            //'details' => htmlspecialchars($param['details']),
            'ficti' => $param['ficti'],
            'browse' => $param['browse'],
            'is_hot' => !empty($param['is_hot']) ? 1 : 0,
            'is_benefit' => !empty($param['is_benefit']) ? 1 : 0,
            'is_best' => !empty($param['is_best']) ? 1 : 0,
            'is_new' => !empty($param['is_new']) ? 1 : 0,
            'is_postage' => !empty($param['is_postage']) ? 1 : 0,
            'up_time' => date("Y-m-d H:i:s",time())
        ];

        //图片上传(单图)
        if (!empty($request->file('file'))) {
            $file = $request->file('file');
            $path = "/shop/goods/product/img/";
            $url = ImageUtil::i()->upload($file, $path);
        }
        //多图
        if (!empty($request->file('files'))) {
            $files = $request->file('files');
            $path = "/shop/goods/product/slider_img/";
            $urls = ImageUtil::i()->upload($files, $path);
        }

        if (!empty($url)) {
            $save['img'] = $url;
        }
        if (!empty($urls)) {
            $save['slider_img'] = json_encode($urls);
        }

        if (!empty($param['is_show']) && $param['is_show'] == "on") {
            $save['is_show'] = 1;
        }
        if (!empty($param['is_del']) && $param['is_del'] == "on") {
            $save['is_del'] = 1;
        }

        DB::startTrans();
        try{
            ShopGoodsModel::updateShopGoodsWhere([['id', '=', $param['id']]], $save);
            if(!empty($param['select'])){
                //清除
                ShopGoodsCateRelationModel::delShopGoodsCateRelationWhere([['goods_id','=',$param['id']]]);
                $cate_ids = explode(',',$param['select']);
                $data = [];
                foreach ($cate_ids as $cate_id){
                    $arr['goods_id'] = $param['id'];
                    $arr['cate_id'] = $cate_id;
                    $arr['add_time'] = date("Y-m-d H:i:s",time());
                    array_push($data,$arr);
                }
                ShopGoodsCateRelationModel::addShopGoodsCateRelation($data);
            }

            //删除之前的属性
            ShopGoodsAttrModel::delShopGoodsAttrWhere([['goods_id', '=', $param['id']]]);
            ShopGoodsAttrValueModel::delShopGoodsAttrValueWhere([['goods_id', '=', $param['id']]]);
            //有属性
            if(!empty($param['attr'])){
                foreach ($param['attr'] as $item){
                    $attr_data = [
                        'goods_id'=>$param['id'],
                        'attr_name'=>$item[0],
                        'attr_values'=>$item[1]
                    ];
                    ShopGoodsAttrModel::addShopGoodsAttr($attr_data);
                }
                if(!empty($param['suk'])){
                    foreach ($param['suk'] as $k=>$item){
                        $attr_value = [
                            'goods_id'=>$param['id'],
                            'suk'=>$param['suk'][$k],
                            'stock'=>!empty($param['attr_stock'][$k]) ? $param['attr_stock'][$k] : 0,
                            'sales'=>!empty($param['attr_sales'][$k]) ? $param['attr_sales'][$k] : 0,
                            'integral'=>!empty($param['attr_integral'][$k]) ? $param['attr_integral'][$k] : 0,
                            'price'=>!empty($param['attr_price'][$k]) ? $param['attr_price'][$k] : 0,
                            'vip_price'=>!empty($param['attr_vip_price'][$k]) ? $param['attr_vip_price'][$k] : 0,
                            'unique'=>uniqid($param['id']),
                            'cost'=>!empty($param['attr_cost'][$k]) ? $param['attr_cost'][$k] : 0,
                        ];
                        ShopGoodsAttrValueModel::addShopGoodsAttrValue($attr_value);
                    }
                }
            }
            DB::commit();
            return Util::returnJson(self::CODE_SUCCESS, null, "修改成功");
        }catch (Exception $e){
            DB::rollBack();
            return Util::returnJson(self::CODE_ERROR, null, "修改失败2");
        }
    }

    /**
     * 修改类型
     * @param Request $request
     * @return array
     */
    public function editShopGoodsType(Request $request)
    {
        $param = $request->post();
        if (!empty($param['is_show'])) {
            if($param['is_show'] == "on"){
                $save['is_show'] = 1;
            }else{
                $save['is_show'] = 0;
            }
        }
        if (!empty($param['is_del'])) {
            if($param['is_del'] == "on"){
                $save['is_del'] = 1;
            }else{
                $save['is_del'] = 0;
            }
        }

        $flag = ShopGoodsModel::updateShopGoodsWhere([['id', '=', $param['id']]], $save);
        if ($flag) {
            return Util::returnJson(self::CODE_SUCCESS, null, "修改成功");
        } else {
            return Util::returnJson(self::CODE_ERROR, null, "修改失败1");
        }
    }

    /**
     * 删除
     * @param Request $request
     * @return array
     */
    public function delShopGoods(Request $request)
    {
        $param = $request->param();
        $id = !empty($param['id']) ? $param['id'] : 0;
        //开启事务
        DB::startTrans();
        try {
            //中间逻辑代码
            $flag = ShopGoodsModel::delShopGoodsWhere([['id', '=', $id]]);
            if ($flag) {
                //删除分类
                ShopGoodsCateRelationModel::delShopGoodsCateRelationWhere([['goods_id','=',$id]]);
                //删除之前的属性
                ShopGoodsAttrModel::delShopGoodsAttrWhere([['goods_id', '=', $id]]);
                ShopGoodsAttrValueModel::delShopGoodsAttrValueWhere([['goods_id', '=', $id]]);
                DB::commit();
                return Util::returnJson(self::CODE_SUCCESS, null, "删除成功");
            } else {
                DB::rollBack();
                return Util::returnJson(self::CODE_ERROR, null, "删除失败");
            }
        } catch (Exception $e) {
            //接收异常处理并回滚
            //回滚事务
            DB::rollBack();
            return Util::returnJson(self::CODE_ERROR, $e, "删除失败");
        }
    }

}
